package com.suse.service.admin.statistics.controller;

import com.suse.common.config.response.ApiException;
import com.suse.common.config.response.R;
import com.suse.common.util.date.DateUtil;
import com.suse.service.admin.statistics.service.DailyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Date;

/**
 * <p>
 * 网站统计日数据 前端控制器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-22
 */
@Slf4j
@Api(tags = "统计接口")
@RestController
@RequestMapping("/daily")
@CrossOrigin
public class DailyController {

    @Resource
    private DailyService dailyService;

    @ApiOperation(value = "通过日期生成当天的统计信息")
    @GetMapping("/create/{date}")
    public R createStatisticsByDate(@PathVariable("date") String date) {
        return dailyService.createStatisticsByDate(date);
    }

    /**
     * LocalDate 没有维护时间和时区信息 接收参数之后时区将不可被改变
     * 用 Date 接收之后再转成 LocalDate
     * @param dateScope 日期范围
     * @return R
     */
    @ApiOperation(value = "获取指定日期范围的统计数据")
    @PostMapping("/chartData")
    public R getChartData(@RequestBody Date[] dateScope) {
        // LocalDate 没有维护时间和时区信息 转换之后时区将不可被改变
        log.info(Arrays.toString(dateScope));
        // 用 Date 接收之后再转成 LocalDate
        LocalDate[] localDateScope = DateUtil.localDates(dateScope);
        // 参数格式校验
        if (dateScope.length != 2) {
            throw new ApiException("日期范围参数格式错误！");
        }
        LocalDate begin = localDateScope[0];
        LocalDate end = localDateScope[1];
        if (begin.isAfter(end)) {
            throw new ApiException("日期范围参数格式错误！");
        }
        return dailyService.getChartData(localDateScope);
    }

}

